﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using GetItemTester;
using eBay.Service.Call;
using eBay.Service.Core.Sdk;

namespace MultiThread
{
    public partial class FetchTokenForm : Form
    {
        private string sessionId;
        public FetchTokenForm()
        {
            InitializeComponent();
        }

        private void btnGo_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textBox1.Text.Trim()))
            {
                MessageBox.Show(this, "Please input a valid eBay User ID.", "Warning");
                return;
            }
           
            ApiContext context = eBayApi.GetEmptyContext(string.Empty, textBox1.Text.Trim());

            sessionId = eBayApi.GetSessionId(context, eBayApi.LoadAppConfig("RunName"));


            this.webBrowser1.Navigate(eBayApi.LaunchSignInPage(context, sessionId));
        }

        private void btnFetchToken_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textBox1.Text.Trim()))
            {
                MessageBox.Show(this, "Please input a valid eBay User ID.", "Warning");
                return;
            }

            if (string.IsNullOrEmpty(sessionId))
            {
                MessageBox.Show(this, "Please click Go to start an authorization process firstly.", "Warning");
                return;
            }
           

            ApiContext context = eBayApi.GetEmptyContext(string.Empty, textBox1.Text.Trim());

            //FetchToken
            context.ApiCredential.eBayAccount = null;
            FetchTokenCall fetchTokenCall = new FetchTokenCall(context);
            string token = fetchTokenCall.FetchToken(sessionId);
            if (!string.IsNullOrEmpty(token))
            {
                context.ApiCredential.eBayToken = token;
                if(this.Owner !=null)
                {
                    Form1 parent = (this.Owner as Form1);
                    parent.eBayToken = token;
                    parent.eBayUser = textBox1.Text.Trim();

                    System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

                    config.AppSettings.Settings["UserAccount.ApiToken"].Value = token;
                    config.AppSettings.Settings["eBayUser"].Value = textBox1.Text.Trim();
                    config.Save(ConfigurationSaveMode.Modified);

                }
                MessageBox.Show(this, "Token is fetched succesfully,Now you are ready to upload pictures to eBay picture server with this ebay account.", "Information");
                this.Close();

            }


        }


    }
}
